//
//  NDImagePicker.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/29.
//

import SwiftUI
import UIKit

struct NDImagePicker: UIViewControllerRepresentable {
    @Environment(\.presentationMode) var presentationMode
    @Binding var selectedImage: UIImage?
    var sourceType: UIImagePickerController.SourceType = .camera
    var isFront: Bool = false
    var onImageSelected: ((UIImage) -> Void)?

    func makeUIViewController(context: UIViewControllerRepresentableContext<NDImagePicker>) -> UIImagePickerController {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = sourceType
        imagePicker.delegate = context.coordinator
        
        if isFront {
            imagePicker.cameraDevice = .front
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.hiddeCameraLimitActionView(actionView: imagePicker.view)
            }
        }
        return imagePicker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<NDImagePicker>) {
        // 更新控制器时的操作，通常留空
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        let parent: NDImagePicker

        init(_ parent: NDImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let image = info[.originalImage] as? UIImage {
                parent.selectedImage = image
                parent.onImageSelected?(image) 
            }
            parent.presentationMode.wrappedValue.dismiss()
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
    
    func hiddeCameraLimitActionView(actionView: UIView) {
        let name = "CAMFlipButton"
        for view in actionView.subviews {
            if view.description.contains(name) {
                view.isHidden = true
                return
            }
            hiddeCameraLimitActionView(actionView: view)
        }
    }
}
